package listener;

import base.BaseFlow;
import common.ScreenShot;
import common.utils.LeoLogger;
import org.openqa.selenium.WebDriver;
import org.testng.ITestResult;
import org.testng.TestListenerAdapter;

/**
 * BaseFlow 默认监听器
 *
 * @author Vincent-Li
 */
public class DefaultBaseFlowListener extends TestListenerAdapter {

    /**
     * onTestFailure，用例执行失败自动截图并将截图添加到allure报告
     */
    @Override
    public void onTestFailure(ITestResult tr) {
        super.onTestFailure(tr);
        try {
            BaseFlow bf = (BaseFlow) tr.getInstance();
            WebDriver driver = bf.getDriver();
            if (driver != null) {
                ScreenShot.attachScreenShotToAllure(driver);
            }
        } catch (ClassCastException e) {
            LeoLogger.logCaseStep("No inheritance of BaseFlow, can not take screenshot");
        }

    }

    /**
     * onConfigurationFailure，当@BeforeClass 或者@BeforeMethod 发生异常或失败，自动退出driver
     */
    @Override
    public void onConfigurationFailure(ITestResult tr) {
        super.onConfigurationFailure(tr);
        try {
            BaseFlow bf = (BaseFlow) tr.getInstance();
            WebDriver driver = bf.getDriver();
            if (driver != null) {
                driver.quit();
            }
        } catch (ClassCastException e) {
            LeoLogger.logCaseStep("No inheritance of BaseFlow, no need to quit driver");
        }

    }
}
